<?php
namespace app\admin\controller;
use app\admin\controller\Base;
use app\admin\model\Admin;
use app\admin\model\Roles;
use app\common\util\TreeUtil;
use \think\Db;

/**
 * 权限管理
 * @author xiegaolei
 *
 */
class Manager extends Base
{
	
	/**
	 * 管理员列表
	 */
    public function adminList(){
    	
    	if ($this->request->isPost()){
    		
    		$draw = input('draw',1,'intval');
    		//排序设置
    		$mycolumns = input('mycolumns/a','');
    		$myorder = input('order/a','');
    		if (empty($myorder)||empty($mycolumns)) {
    			$order = 'id asc';
    		}else{
    			$order = '';
    			foreach ($myorder as $key => $v) {
    				$order .= $mycolumns[$v['column']].' '.$v['dir'].' ,';
    			}
    			$order = rtrim($order , ',');
    		}
    		
    		$admin = new Admin();
    		$lists = $admin->order($order)->select();
    		foreach ($lists as $key => $v){
    			$lists[$key]['role'] = Db::name('auth_group_access')->alias('a')->join('__AUTH_GROUP__ b','a.group_id= b.id')->where('a.uid',$v['id'])->value('title');
    		}
    		
    		$result['draw'] = $draw;
    		$result['recordsTotal'] = $admin->count();
    		$result['recordsFiltered'] = $result['recordsTotal'];
    		$result['data'] = $lists;
    	
    		json_return($result);
    	
    	}else{
    		return $this->fetch();
    	}
    }
      
    
    /**
     * 添加管理员
     */
    public function adminAdd(){
    	
    	$groups = Db::name('auth_group')->order('id','asc')->select();
    	$this->assign('groups', $groups);
    	
    	return $this->fetch();
    }
    
    /**
     * 编辑管理员
     */
    public function adminEdit(){
    	 
    	$groups = Db::name('auth_group')->order('id','asc')->select();
    	$this->assign('groups', $groups);
    	
    	$id = input('id','0','int');
    	if (empty($id)){
    		exit('参数有误！');
    	}
    	
    	$admin = new Admin();
    	$info = $admin->where('id',$id)->find();
    	$this->assign('info',$info);
     	
    	$group_id = Db::name('auth_group_access')->where('uid',$id)->value('group_id');
    	$this->assign('group_id',$group_id);
    	
    	return $this->fetch();
    }
    
    
    /**
     * 保存管理员
     */
    public function adminSave(){
		//验证规则
    	$rule = [
    			'group'  => ['require','gt'=>'0'],
    			'username'  => ['require','max'=>'25','alpha'],
    			'mobile'   => ['regex'=>'/1[3458]{1}\d{9}$/'],
    			'email' => ['email'],
    	];
    	
    	//提示信息
    	$msg = [
    			'group' => '请选择角色',
    			'username.require' => '账号必须',
    			'username.max'     => '账号最多不能超过25个字符',
    			'username.alpha'     => '账号必须是字母',
    			'mobile.regex'   => '手机格式错误',
    			'email'        => '邮箱格式错误',
    	];
    	//接收数据
    	$data = [
    			'group'  => input('group','','trim'),
    			'username'  => input('username','','trim'),
    			'mobile'   => input('mobile','','trim'),
    			'email' => input('email','','trim'),
    			'password' => input('password','','trim'),
    			'isEnabled' => input('isEnabled',0,'int')
    	];
    	
    	//验证输入数据合法性
    	$validate = new \think\Validate($rule, $msg);
    	$result   = $validate->check($data);
    	if (!$result){
    		$error = $validate->getError();
    		ajax_return_error($error);
    	}
    	
    	$id = input('id','0','int');
    	$admin = new Admin();
    	if ($id){
    		
    		if($this->checkAdmin($data['username']) && $id != $this->checkAdmin($data['username'])){
    			ajax_return_error('该账号已存在');
    		}
    		
    		$res = $admin->allowField(true)->save($data,['id'=>$id]);
    	}else{
    		
    		if($this->checkAdmin($data['username'])){
    			ajax_return_error('该账号已存在');
    		}
    		
    		$res = $admin->allowField(true)->save($data);
    	}
    	 
    	
    	if ($res == false){
    		ajax_return_error('操作失败！');
    	}
    	
    	if (!$id){
    		$id = $admin->getLastInsertId();
    	}
    	
    	//角色更新
    	$group_id = Db::name('auth_group_access')->where('uid',$id)->value('group_id');
    	if(empty($group_id)){
    		//添加
    		Db::name('auth_group_access')->insert(['group_id' => $data['group'],'uid'=>$id]);
    	}elseif($data['group'] != $group_id) {
    		//更新
    		Db::name('auth_group_access')->where('uid',$id)->update(['group_id' => $data['group']]);
    	} 
    	 
    	
    	ajax_return_ok([],'操作成功！');
    }
    
    /**
     * 删除
     */
    public function adminDel(){
    	$id = input('id','0','int');
    	if ($id == 0) {
    		exit('参数有误！');
    	}else{
    		
    		Db::name('auth_group_access')->where('uid',$id)->delete();
    	
    		if (Db::name('admin')->where('id',$id)->delete()) {
    			ajax_return_ok([],'操作成功！');
    		}else{
    			ajax_return_error('操作失败！');
    		}
    	
    	}
    }
    
    /**
     * 角色列表
     */
    public function rolesList(){
    	 
    	if ($this->request->isPost()){
    
    		$draw = input('draw',1,'intval');
    		//排序设置
    		$mycolumns = input('mycolumns/a','');
    		$myorder = input('order/a','');
    		if (empty($myorder)||empty($mycolumns)) {
    			$order = 'id asc';
    		}else{
    			$order = '';
    			foreach ($myorder as $key => $v) {
    				$order .= $mycolumns[$v['column']].' '.$v['dir'].' ,';
    			}
    			$order = rtrim($order , ',');
    		}
    
    		$roles = new Roles();
    		$lists = $roles->order($order)->select();
    
    		$result['draw'] = $draw;
    		$result['recordsTotal'] = $roles->count();
    		$result['recordsFiltered'] = $result['recordsTotal'];
    		$result['data'] = $lists;
    		 
    		json_return($result);
    		 
    	}else{
    		return $this->fetch();
    	}
    }
    
    /**
     * 添加角色
     */
    public function rolesAdd(){
    	 
    	$rules = Db::name('auth_rule')->where('status',1)->order('sorts','asc')->select();
    	//格式化成树形
    	$rules = TreeUtil::listToTreeMulti($rules, 0, 'id', 'pid', 'child');
    	
    	$this->assign('rules', $rules);
    	return $this->fetch();
    }
    
    /**
     * 编辑角色
     */
    public function rolesEdit(){
    
    	$rules = Db::name('auth_rule')->where('status',1)->order('sorts','asc')->select();
    	//格式化成树形
    	$rules = TreeUtil::listToTreeMulti($rules, 0, 'id', 'pid', 'child');
    	$this->assign('rules', $rules);
    	 
    	$id = input('id','0','int');
    	if (empty($id)){
    		exit('参数有误！');
    	}
    	 
    	$roles = new Roles();
    	$info = $roles->where('id',$id)->find();
    	$info['rules'] = explode(',', $info['rules']);
    	$this->assign('info',$info);
    	 
    	return $this->fetch();
    }
    
    /**
     * 保存角色
     */
    public function rolesSave(){
    	 
    	//验证规则
    	$rule = [
    			'title'  => ['require'],
    			'rules'  => ['require']
    	];
    	 
    	//提示信息
    	$msg = [
    			'title' => '名称必填',
    			'rules' => '权限必选',
    	];
    	//接收数据
    	$data = [
    			'title'  => input('title','','trim'),
    			'rules'  => input('rules/a',''),
    			'status' => input('status',0,'int')
    	];
    	 
    	//验证输入数据合法性
    	$validate = new \think\Validate($rule, $msg);
    	$result   = $validate->check($data);
    	if (!$result){
    		$error = $validate->getError();
    		ajax_return_error($error);
    	}
    	
    	$data['rules'] =implode(',', $data['rules']);
    	
    	$id = input('id','0','int');
    	$roles = new Roles();
    	if ($id){
    		
    		if($this->checkRoles($data['title']) && $id != $this->checkRoles($data['title'])){
    			ajax_return_error('该名称已存在');
    		}
    		
    		$res = $roles->allowField(true)->save($data,['id'=>$id]);
    	}else{
    		
    		if($this->checkRoles($data['title'])){
    			ajax_return_error('该名称已存在');
    		}
    		
    		$res = $roles->allowField(true)->save($data);
    	}
    	  
    	if ($res){
    		ajax_return_ok([],'操作成功！');
    	}else{
    		ajax_return_error('操作失败！');
    	}
    	
    }
    
    
    /**
     * 删除
     */
    public function rolesDel(){
    	$id = input('id','0','int');
    	if ($id == 0) {
    		exit('参数有误！');
    	}else{
    		 
    		if (Db::name('auth_group')->where('id',$id)->delete()) {
    			ajax_return_ok([],'操作成功！');
    		}else{
    			ajax_return_error('操作失败！');
    		}
    		 
    	}
    }
    
     
    
    /**
     * 权限列表
     */
    public function rulesList(){
    
    	if ($this->request->isPost()){
    
    		$draw = input('draw',1,'intval');
    		//排序设置
    		$mycolumns = input('mycolumns/a','');
    		$myorder = input('order/a','');
    		if (empty($myorder)||empty($mycolumns)) {
    			$order = 'id asc';
    		}else{
    			$order = '';
    			foreach ($myorder as $key => $v) {
    				$order .= $mycolumns[$v['column']].' '.$v['dir'].' ,';
    			}
    			$order = rtrim($order , ',');
    		}
    
    		$roles = Db::name('auth_rule');
    		$lists = $roles->order($order)->select();
    		foreach ($lists as $key => $v){
    			if ($v['status']){
    				$lists[$key]['status'] = '正常';
    			}else{
    				$lists[$key]['status'] = '禁用';
    			}
    		}
    		
    		//格式化处理
    		$lists = TreeUtil::listToTreeOne( $lists ,  0 , '|— ' , 'id' , 'pid' , 'html');
    		
    		$result['draw'] = $draw;
    		$result['recordsTotal'] = $roles->count();
    		$result['recordsFiltered'] = $result['recordsTotal'];
    		$result['data'] = $lists;
    		 
    		json_return($result);
    		 
    	}else{
    		return $this->fetch();
    	}
    }
    
    
    
    /**
     * 添加权限
     */
    public function rulesAdd(){
    
    	$rules = Db::name('auth_rule')->where('status',1)->order('sorts','asc')->select();
    	//格式化处理
    	$rules = TreeUtil::listToTreeOne( $rules ,  0 , '|— ' , 'id' , 'pid' , 'html');
    	
    	$this->assign('rules', $rules);
    	return $this->fetch();
    }
    
    /**
     * 编辑权限
     */
    public function rulesEdit(){
    
    	$id = input('id','0','int');
    	if (empty($id)){
    		exit('参数有误！');
    	}
    	$rules = Db::name('auth_rule')->where('status',1)->order('sorts','asc')->select();
    	//格式化处理
    	$rules = TreeUtil::listToTreeOne( $rules ,  0 , '|— ' , 'id' , 'pid' , 'html');
    	$this->assign('rules', $rules);
    	
    	$info = Db::name('auth_rule')->where('id',$id)->find();
    	$this->assign('info',$info);
    	
    	return $this->fetch();
    }
    
    /**
     * 保存权限
     */
    public function rulesSave(){
    
    	//验证规则
    	$rule = [
    			'title'  => ['require'],
    			'name'  => ['require']
    	];
    
    	//提示信息
    	$msg = [
    			'title' => '名称必填',
    			'name' => '标识必填'
    	];
    	//接收数据
    	$data = [
    			'pid'  => input('pid','','int'),
    			'title'  => input('title','','trim'),
    			'name'  => input('name','','trim'),
    			'status' => input('status',0,'int')
    	];
    
    	//验证输入数据合法性
    	$validate = new \think\Validate($rule, $msg);
    	$result   = $validate->check($data);
    	if (!$result){
    		$error = $validate->getError();
    		ajax_return_error($error);
    	}                                                                  
    	 
    	$id = input('id','0','int');
    	$rules = Db::name('auth_rule');
    	if ($id){
    		$res = $rules->where('id',$id)->update($data);
    	}else{
    		$res = $rules->insert($data);
    	}
    	 
    	if ($res){
    		  
    		ajax_return_ok([],'操作成功！');
    	}else{
    		ajax_return_error('操作失败！');
    	}
    	 
    }
    
    
    /**
     * [sortColum 栏目排序]
     * @return [type] [description]
     */
    public function rulesSort(){
    	$listOrder = $_POST['listOrder'];
    	
    	if (empty($listOrder)) {
    		ajax_return_error('没有数据！');
    	}else{
    		$rules = Db::name('auth_rule');
    		foreach ($listOrder as $id => $sorts){
    			$rules->where('id', $id)->update(['sorts'=>$sorts]);
    		}
    		
    		ajax_return_ok([],'操作成功！');
    	}
    
    }
    
    
    
    /**
     * 删除
     */
    public function rulesDel(){
    	$id = input('id','0','int');
    	if ($id == 0) {
    		exit('参数有误！');
    	}else{
    		 
    		if (Db::name('auth_rule')->where('id',$id)->delete()) {
    			ajax_return_ok([],'操作成功！');
    		}else{
    			ajax_return_error('操作失败！');
    		}
    		 
    	}
    }
    
    
    
    /**
     * [checkAdmin 检测用户名是否存在]
     * @param  [type] $name [description]
     * @return [type]       [description]
     */
    protected function checkAdmin($name){
    	$id = Db::name('admin')->where('username',$name)->value('id');
    	if (empty($id)) {
    		return 0;
    	}else{
    		return $id;
    	}
    }
    
    
    /**
     * [checkName 检测角色是否存在]
     * @param  [type] $name [description]
     * @return [type]       [description]
     */
    protected function checkRoles($name){
    	$id = Db::name('auth_group')->where('title',$name)->value('id');
    	if (empty($id)) {
    		return 0;
    	}else{
    		return $id;
    	}
    }
    
    
    
}
